package top.chatgqt.SmartChargeStation.netty.server.utils;

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import top.chatgqt.SmartChargeStation.protocol.mqtt.message.ChargePayload;

@Slf4j
public class HTTPUtils {

    /**
     * POST请求
     *
     * @param payload
     */
    public static void doPOST(ChargePayload payload) {
        String json = JSON.toJSONString(payload);
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        RequestBody requestBody = RequestBody.create(mediaType, json);

        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url("http://127.0.0.1:8080/mqtt/send")
                .post(requestBody)
                .build();

        isOk(client, request);
    }

    /**
     * 判断请求是否成功
     *
     * @param client
     * @param request
     */
    private static void isOk(OkHttpClient client, Request request) {
        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                String body = null;
                if (response.body() != null) {
                    body = response.body().string();
                }
                log.info("API返回信息:" + body);
            }
        } catch (Exception e) {
            log.error("调用失败");
            e.printStackTrace();
        }
    }
}
